package com.wbao.dianniu.ui;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;

import com.igexin.sdk.PushManager;
import com.lhh.apst.library.AdvancedPagerSlidingTabStrip2;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.qcloud.timchat.utils.LoginBusiness;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.SchemeEnum;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.DnApplication;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.service.DemoIntentService;
import com.wbao.dianniu.service.GTPushService;
import com.wbao.dianniu.tabstrip.fragments.APSTSViewPager;
import com.wbao.dianniu.tabstrip.fragments.FirstFragment;
import com.wbao.dianniu.tabstrip.fragments.FourthFragment;
import com.wbao.dianniu.tabstrip.fragments.SecondFragment;
import com.wbao.dianniu.tabstrip.fragments.ThirdFragment;
import com.wbao.dianniu.update.ChatUnreadChangeManger;
import com.wbao.dianniu.update.UpdateManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;

import java.util.ArrayList;

public class MainActivity extends FragmentActivity implements UpdateManager.ICheckCompletedListener, ChatUnreadChangeManger.IUnreadChangeListener {
    public AdvancedPagerSlidingTabStrip2 mAPSTS;
    public APSTSViewPager mVP;

    private static final int VIEW_FIRST = 0;
    private static final int VIEW_SECOND = 1;
    private static final int VIEW_THIRD = 2;
    private static final int VIEW_FOURTH = 3;

    private final int VIEW_SIZE = 4;

    private FirstFragment fistfragment;
    private SecondFragment secondFragment;
    private ThirdFragment mThirdFragment = null;
    private FourthFragment fourthFragment;

    private long firstTime;
    private int showPage;
    private UpdateManager updateManager;
    private static final String TAG = "GetuiSdkDemo";
    // DemoPushService.class 自定义服务名称, 核心服务
    private Class userPushService = GTPushService.class;
    private static final int REQUEST_PERMISSION = 0;
    private int notifyUnreadCounts = 0;
    private int chatUnreadCounts = 0;
    public static final String ACTION_OFFLINE_NOTIFY = "com.wbao.dianniu.action.offline.notify";
    private OfflineNotifyReceiver offlineNotifyReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_main_inc);

        Intent intent = getIntent();
        showPage = intent.getIntExtra(Const.INTENT_IS_MESSAGE, VIEW_FIRST);
        findViews();
        init();
        checkUpdate();
        schemeiInto();

        initGTPush();
        initOfflineReceiver();

    }

    private void initOfflineReceiver() {
        if (null == offlineNotifyReceiver) {
            // 动态注册广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_OFFLINE_NOTIFY);
            offlineNotifyReceiver = new OfflineNotifyReceiver();
            // 注册前先移除广播
            registerReceiver(offlineNotifyReceiver, filter);
        }
    }


    private void initGTPush() {
        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }

        PushManager.getInstance().initialize(this.getApplicationContext(), GTPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            } else {
                Log.e(TAG, "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                        + "functions will not work");
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void schemeiInto() {
        Intent intent = getIntent();
        String type = intent.getStringExtra(Const.INTENT_SCHEME_TYPE);
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != type && null != id) {
            Class cls = null;
            if (SchemeEnum.QUEST.equals(type)) {
                cls = QaDetailActivity.class;
            } else if (SchemeEnum.AM.equals(type)) {
                cls = AmDetailActivity.class;
            } else if (SchemeEnum.CARD.equals(type)) {
                cls = HeadInfoActivity.class;
            } else if (SchemeEnum.JOB.equals(type)) {
                cls = JobDetailsActivity.class;
            } else if (SchemeEnum.RECRUIT.equals(type)) {
                cls = RecruitDetailsActivity.class;
            } else if (SchemeEnum.ACT.equals(type)) {
                cls = ActivityDetail.class;
            } else if (SchemeEnum.KNOWLEDGE.equals(type)) {
                cls = KnowDetailActivity.class;
            }
            if (null == cls)
                return;
            Intent intoIntent = new Intent();
            intoIntent.putExtra(Const.INTENT_SCHEME_ID, id);
            intoIntent.setClass(MainActivity.this, cls);
            startActivity(intoIntent);
        }
    }

    /**
     * 检测更新
     */
    private void checkUpdate() {
        updateManager = new UpdateManager(this);
        updateManager.addCheckListener(this);
        updateManager.checkUpdate();
        /*long time = SharedPreferencesUtils.getUpdateTime(this);
        if (System.currentTimeMillis() - time > 1000 * 60 * 60 * 24) {
            SharedPreferencesUtils.setUpdateTime(System.currentTimeMillis());
            // 对比版本号更新
            int version = Utils.getVersionCode(this);
            int serviceCode = GlobalContext.versionCode;
            if (serviceCode > version) {
                UpdateManager update = new UpdateManager(this);
                update.checkUpdate();
            }
        }*/
    }

    private void findViews() {
        mAPSTS = findViewById(R.id.main_tabs);
        mVP = findViewById(R.id.main_apsts);
    }

    private void init() {
        mVP.setOffscreenPageLimit(VIEW_SIZE);
        mVP.setCurrentItem(showPage);
        mVP.setNoFocus(true);
        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
        mVP.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mAPSTS.setViewPager(mVP);
        showUnreadCounts();

        ChatUnreadChangeManger.getInstance().addUnreadChangeListener(this);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 800) {// 如果两次按键时间间隔大于800毫秒，则不退出
                Notification.toast(MainActivity.this, "再按一次退出程序");
                firstTime = secondTime;// 更新firstTime
                return true;
            } else {
//				LoginSampleHelper.getInstance().loginOut_Sample();
//				System.exit(0);// 否则退出程序 杀死进程
                this.finish();
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void checkCompleted() {

    }

    @Override
    public void noCheck() {

    }

    @Override
    public void noPermission() {
        PermissionUtils.getInstance().showMsg(this, "更新失败，没有读取权限，\n请点击\"设置\"-\"权限管理\"-打开所有权限");
    }

    @Override
    public void unreadChange(int idType) {

    }

    @Override
    public void addAllNotifyUnread(int counts) {
        notifyUnreadCounts += counts;
        showUnreadCounts();
    }

    @Override
    public void minusAllNotifyUnread(int counts) {
        notifyUnreadCounts -= counts;
        showUnreadCounts();
    }

    @Override
    public void addAllChatUnread(int counts) {
        chatUnreadCounts += counts;
        showUnreadCounts();
    }

    @Override
    public void minusAllChatUnread(int counts) {
        chatUnreadCounts -= counts;
        showUnreadCounts();
    }

    @Override
    public void setChatUnread(int counts) {
        chatUnreadCounts = counts;
        showUnreadCounts();
    }

    @Override
    public void setNofifyUnread(int counts) {
        notifyUnreadCounts = counts;
        showUnreadCounts();
    }

    private class FragmentAdapter extends FragmentStatePagerAdapter implements AdvancedPagerSlidingTabStrip2.IconTabProvider {

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position >= 0 && position < VIEW_SIZE) {
                switch (position) {
                    case VIEW_FIRST:
                        if (null == fistfragment)
                            fistfragment = FirstFragment.instance(MainActivity.this);
                        return fistfragment;
                    case VIEW_SECOND:
                        if (null == secondFragment)
                            secondFragment = SecondFragment.instance(MainActivity.this);
                        return secondFragment;
                    case VIEW_THIRD:
                        if (null == mThirdFragment)
                            mThirdFragment = ThirdFragment.instance();
                        return mThirdFragment;
                    case VIEW_FOURTH:
                        if (null == fourthFragment) {
                            fourthFragment = FourthFragment.instance();
                        }
                        return fourthFragment;
                    default:
                        break;
                }
            }
            return null;
        }

        @Override
        public int getCount() {
            return VIEW_SIZE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position >= 0 && position < VIEW_SIZE) {
                switch (position) {
                    case VIEW_FIRST:
                        return "电纽";
                    case VIEW_SECOND:
                        return "发现";
                    case VIEW_THIRD:
                        return "消息";
                    case VIEW_FOURTH:
                        return "我";
                    default:
                        break;
                }
            }
            return null;
        }

        @SuppressWarnings("unchecked")
        @Override
        public Integer getPageIcon(int index) {
            if (index >= 0 && index < VIEW_SIZE) {
                switch (index) {
                    case VIEW_FIRST:
                        return R.drawable.home_main_icon_one_n;
                    case VIEW_SECOND:
                        return R.drawable.home_main_icon_two_n;
                    case VIEW_THIRD:
                        return R.drawable.home_main_icon_third_n;
                    case VIEW_FOURTH:
                        return R.drawable.home_main_icon_four_n;
                    default:
                        break;
                }
            }
            return 0;
        }

        @SuppressWarnings("unchecked")
        @Override
        public Integer getPageSelectIcon(int index) {
            if (index >= 0 && index < VIEW_SIZE) {
                switch (index) {
                    case VIEW_FIRST:
                        return R.drawable.home_main_icon_one_f;
                    case VIEW_SECOND:
                        return R.drawable.home_main_icon_two_f;
                    case VIEW_THIRD:
                        return R.drawable.home_main_icon_third_f;
                    case VIEW_FOURTH:
                        return R.drawable.home_main_icon_four_f;
                    default:
                        break;
                }
            }
            return 0;
        }

        @Override
        public Rect getPageIconBounds(int position) {
            return null;
        }
    }

    /**
     * 回调接口
     *
     * @author zhaoxin5
     */
    public interface MyTouchListener {
        void onTouchEvent(MotionEvent event);
    }

    /*
     * 保存MyTouchListener接口的列表
     */
    private ArrayList<MyTouchListener> myTouchListeners = new ArrayList<MyTouchListener>();

    /**
     * 提供给Fragment通过getActivity()方法来注册自己的触摸事件的方法
     *
     * @param listener
     */
    /*public void registerMyTouchListener(MyTouchListener listener) {
        myTouchListeners.add(listener);
    }*/

    /**
     * 提供给Fragment通过getActivity()方法来取消注册自己的触摸事件的方法
     *
     * @param listener
     */
    /*public void unRegisterMyTouchListener(MyTouchListener listener) {
        myTouchListeners.remove(listener);
    }*/

    /**
     * 分发触摸事件给所有注册了MyTouchListener的接口
     */
    /*@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for (MyTouchListener listener : myTouchListeners) {
            listener.onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }*/
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);       //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private synchronized void showUnreadCounts() {
        int allCounts = 0;
        allCounts = notifyUnreadCounts + chatUnreadCounts;
        if (allCounts > 99) {
            mAPSTS.showDot(VIEW_THIRD, "99+");
        } else if (allCounts > 0) {
            mAPSTS.showDot(VIEW_THIRD, String.valueOf(allCounts));
        } else {
            mAPSTS.hideDot(2);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != updateManager) {
            updateManager.removeCheckListener();
        }
        ChatUnreadChangeManger.getInstance().removeUnreadChangeListener(this);
        if (null != offlineNotifyReceiver) {
            // 注销广播
            unregisterReceiver(offlineNotifyReceiver);
        }
    }

    private class OfflineNotifyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_OFFLINE_NOTIFY == intent.getAction()) {
//                forceOfflineShow(MainActivity.this);
                offlineNotify();
            }
        }
    }

    private void offlineNotify() {
        Intent i = new Intent(this, ActDialog.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    /**
     * 重新登录
     */
    /*private void reginLogin() {
        GlobalUserData userData = new GlobalUserData();
        LoginBusiness.loginIm(userData.getEnvironemt() + GlobalContext.getAccountId(), userData.getUserSig(), new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "onError..." + i + "  s:" + s);
            }

            @Override
            public void onSuccess() {
                Log.e(TAG, " region login onSuccess...");
            }
        });
    }*/

}
